<template>
    <div class="base-page"  :style="{ height:screenHeight-20+'px'}">
        <!-- <div class="left">
            <select-org @select="onSelectOrg" />
        </div> -->
        <!-- 列表 -->
        <div style="height:100%"  class="right" v-show="viewList === true">
            <div class="e-table">
                <div class="top right-div1">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="primary" size="mini"
                                @click="addData"
                                class="btn-greenYellow"
                            >新增</el-button>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                    </div>
                </div>
            </div>
            <div class="e-table" >
                <el-table
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    ref="table"
                    :cell-class-name="cellClsNm"
                    @cell-mouse-enter="cellMouseEnter"
                    @cell-mouse-leave="cellMouseLeave"
                    @current-change="handleCurrentChange"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'table' }"
                    class="table"
                >
                    <el-table-column label="序号" type="index" width="55" fixed> </el-table-column>
                    <el-table-column show-overflow-tooltip fixed label="操作" width="150">
                        <template slot-scope="{ row }">
                            <div class="oparation_box">
                                <i
                                    class="el-icon-edit"
                                    style="font-size: 24px"
                                    :class="{
                                        'icon-edit-active-color': MouseEnterId == row.id
                                    }"
                                    @click="tableDbEdit(row)"
                                ></i>
                                <i
                                    class="el-icon-delete"
                                    style="font-size: 24px"
                                    :class="{
                                        'icon-delete-active-color': MouseEnterId == row.id
                                    }"
                                    @click="tableDbDelete(row)"
                                ></i>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="outerTypeValue" label="外包方类型" min-width="120" show-overflow-tooltip>
                        <template slot-scope="{ row }">
                            <span>{{ outsourcerType[row.outerTypeValue]}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="equipmentName" label="分子公司汇总评价截止日期" width="200" show-overflow-tooltip>
                        <template slot-scope="{ row }">
                            <span>{{ row.subEndYear + '-' +  row.subEndMonth + '-' +  row.subEndDay}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="specificationModel" label="集团汇总评价截止日期" width="200" show-overflow-tooltip>
                        <template slot-scope="{ row }">
                            <span>{{ row.groupEndYear + '-' +  row.groupEndMonth + '-' +  row.groupEndDay}}</span>
                        </template> </el-table-column>
                    <el-table-column prop="startMonth" label="评价有效期开始日期" width="200" show-overflow-tooltip>
                        <template slot-scope="{ row }">
                            <span>{{ row.startMonth + '-' +  row.startDay}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="offDate" label="不合格时间范围（年）" width="200" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="blackDate" label="黑名单时间范围（年）" width="200" show-overflow-tooltip>
                        <template slot-scope="{ row }">
                            <span>{{ blackDateList.find(x=>x.value === row.blackDate).label }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="getTableData"
                @sizeChange="getTableData"
            />
        </div>
        <!-- 新增编辑界面 -->
        <div class="right" v-if="viewList === 'add' || viewList === 'edit'">
            <div class="e-form" style="padding: 0 10px 10px;">
                <div class="tabs-title">基本信息</div>
                <el-form ref="form" :model="formDataDetail" :rules="rules" label-width="270px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="外包方类型：" prop="outerTypeValue">
                              <el-select
                                    v-model.number="formDataDetail.outerTypeValue"
                                    placeholder="请选择"
                                >
                                    <el-option
                                        v-for="(
                                            item,index
                                        ) in outsourcerType"
                                        :key="item"
                                        :label="item"
                                        :value="index"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="评价有效期开始日期：" prop="startMonth" v-if="formDataDetail.outerTypeValue === 0">
                                <el-select
                                    v-model="formDataDetail.startMonth"
                                    placeholder="请选择"
                                    style="width:49%;margin-right:1%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in month"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                                <el-select
                                    v-model="formDataDetail.startDay"
                                    placeholder="请选择"
                                    style="width:49%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in day(formDataDetail.startMonth,'startDay')"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="分子公司汇总评价截至日期（次年）：" prop="subEndMonth">
                                <el-select
                                    v-model="formDataDetail.subEndMonth"
                                    placeholder="请选择"
                                    style="width:49%;margin-right:1%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in month"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                                <el-select
                                    v-model="formDataDetail.subEndDay"
                                    placeholder="请选择"
                                    style="width:49%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in day(formDataDetail.subEndMonth,'subEndDay')"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="集团汇总评价截至日期（次年）：" prop="groupEndMonth">
                                <el-select
                                    v-model="formDataDetail.groupEndMonth"
                                    placeholder="请选择"
                                    style="width:49%;margin-right:1%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in month"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                                <el-select
                                    v-model="formDataDetail.groupEndDay"
                                    placeholder="请选择"
                                    style="width:49%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in day(formDataDetail.groupEndMonth,'groupEndDay')"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="不合格时间范围（年）：" prop="offDate">
                              <el-select
                                    v-model="formDataDetail.offDate"
                                    placeholder="请选择"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in [1,2,3,4,5]"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="黑名单时间范围（年）：" prop="blackDate">
                                <el-select
                                    v-model="formDataDetail.blackDate"
                                    placeholder="请选择"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in blackDateList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="分子公司汇总评价修改权限：" prop="isSubModify" v-if="formDataDetail.outerTypeValue === 0">
                                <el-select
                                    v-model="formDataDetail.isSubModify"
                                    placeholder="请选择"
                                >
                                    <el-option
                                        v-for="(
                                            item,index
                                        ) in options"
                                        :key="item"
                                        :label="item"
                                        :value="index"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="集团汇总评价修改权限：" prop="isGroupModify" v-if="formDataDetail.outerTypeValue === 0">
                                <el-select
                                    v-model="formDataDetail.isGroupModify"
                                    placeholder="请选择"
                                >
                                    <el-option
                                        v-for="(
                                            item,index
                                        ) in options"
                                        :key="item"
                                        :label="item"
                                        :value="index"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="是否允许补录季度评价：" prop="isModify" v-if="formDataDetail.outerTypeValue === 0">
                                <el-checkbox v-model="formDataDetail.isModify" />
                                <!-- <el-select
                                    v-model="formDataDetail.isModify"
                                    placeholder="请选择"
                                >
                                    <el-option
                                        v-for="(
                                            item,index
                                        ) in [' ','只能降级','可修改为任意等级']"
                                        :key="item"
                                        :label="item"
                                        :value="index"
                                    >
                                    </el-option>
                                </el-select> -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="选择补录截至日期：" prop="workShiftCount" v-if="formDataDetail.outerTypeValue === 0">
                                <el-select
                                    v-model="formDataDetail.modifyEndMonth"
                                    placeholder="请选择"
                                    style="width:49%;margin-right:1%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in month"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                                <el-select
                                    v-model="formDataDetail.modifyEndDay"
                                    placeholder="请选择"
                                    style="width:49%"
                                >
                                    <el-option
                                        v-for="(
                                            item
                                        ) in day(formDataDetail.modifyEndMonth,'modifyEndDay')"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary" size="mini"
                        @click="onSave"
                    >保存</el-button>
                    <el-button type="default" size="mini"
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import Pagination from '@/components/pagination/pagination'
import { debounce, advanceSearch, showLoading, hideLoading } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'
import { evaluationPeriodList, addEvaluationPeriod, updatEevaluationPeriod, deleteEvaluationPeriod, getEvaluationPeriod } from '@/api/base/outsourcer'
import { selectDataClient } from '@/utils/common'
export default {
    components: {
        Pagination,
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
        }),

        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 300) + 'px'
        },
        // 列表高度
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 300) + 'px'
        },
        rightTableHeight2 () {
            return this.screenHeight - 210
        },
        day () {
            return (index, field)=>{
                console.log(index, field)
                if(!index) return []
                const big = [1, 3, 5, 7, 8, 10, 12]
                const small = [4, 6, 9, 11]
                const fn = val=>{
                    let arr = []
                    for(let i = 1;i <= val;i++) {
                        arr.push(i)
                    }
                    return arr
                }
                let dayArr
                if(big.includes(index)) {
                    dayArr = fn(31)
                }
                else if(small.includes(index)) {
                    dayArr = fn(30)
                }else if(index === 2) {
                    dayArr = fn(28)
                }

                if(field && this.formDataDetail[field] > dayArr[dayArr.length - 1]) {
                    this.formDataDetail[field] = dayArr[dayArr.length - 1]
                }

                return dayArr
            }

        },
    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            currentRow: null,
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            options: ['只能降级', '可修改为任意等级'],
            tableData: [],
            formData: {
                'keyword': '',
                'limit': 0,
                'page': 0
            },
            formDataDetail: {},
            MouseEnterId: 0,
            screenWidth: 0,
            screenHeight: 0,
            rules: {
                outerTypeValue: [
                    { required: true, message: '请选择外包方类型', trigger: ['blur', 'change'] },
                ],
                startMonth: [
                    { required: true, message: '请选择日期', trigger: ['blur', 'change'] },
                    { validator: (rule, value, callback)=>{
                        if(this.formDataDetail.startDay) {
                            callback()
                        }else{
                            callback(new Error('请选择日'))
                        }
                    }, trigger: ['blur', 'change'] },
                ],
                subEndMonth: [
                    { required: true, message: '请选择日期', trigger: ['blur', 'change'] },
                    { validator: (rule, value, callback)=>{
                        if(this.formDataDetail.subEndDay) {
                            callback()
                        }else{
                            callback(new Error('请选择日'))
                        }
                    }, trigger: ['blur', 'change'] },
                ],
                groupEndMonth: [
                    { required: true, message: '请选择日期', trigger: ['blur', 'change'] },
                    { validator: (rule, value, callback)=>{
                        if(this.formDataDetail.groupEndDay) {
                            callback()
                        }else{
                            callback(new Error('请选择日'))
                        }
                    }, trigger: ['blur', 'change'] },
                ],
                offDate: [
                    { required: true, message: '请选择不合格时间范围', trigger: ['blur', 'change'] },
                ],
                blackDate: [
                    { required: true, message: '请选择黑名单时间范围', trigger: ['blur', 'change'] },
                ],

            },
            stateList: [
                {
                    label: '停用',
                    value: '1'
                },
                {
                    label: '启用',
                    value: '2'
                },
            ], //设备状态
            outsourcerType: ['分包商', '供应商'],
            month: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], //月份
            blackDateList: [
                { value: 1, label: '1' },
                { value: 2, label: '2' },
                { value: 3, label: '3' },
                { value: 4, label: '4' },
                { value: 5, label: '5' },
                { value: 6, label: '终生' },
            ]
        }
    },
    mounted () {
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
        this.getTableData()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        async getTableData () {
            showLoading()
            try {
                this.formData.limit = this.paginationInfo.pageSize
                this.formData.page = this.paginationInfo.currentPage
                const resData = await evaluationPeriodList(this.formData)
                this.tableData = resData.list
                this.paginationInfo.total = resData.totalCount
                hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        onSelectOrg (val) {
            this.paginationInfo.currentPage = 1
            this.formData = {
                ...this.formData,
                ...val,
            }
            this.getTableData()
        },
        addData () {
            this.formDataDetail = {
                'billDate': '',
                'billNo': '',
                'blackDate': null,
                'endDay': null,
                'endMonth': null,
                'groupEndDay': null,
                'groupEndMonth': null,
                'id': '',
                'isGroupModify': null,
                'isModify': false,
                'isSubModify': null,
                'offDate': null,
                'orgId': '',
                'orgName': '',
                'outerTypeKey': '',
                'outerTypeValue': '',
                'remark': '',
                'startDay': null,
                'startMonth': null,
                'state': null,
                'subEndDay': null,
                'subEndMonth': null
            }
            this.viewList = 'add'
        },
        tableDbEdit (row) {
            getEvaluationPeriod({ id: row.id }).then(res => {
                res.outerTypeValue = Number(res.outerTypeValue)
                this.formDataDetail = res
                this.viewList = 'edit'
            })
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onSearch (e) {
            console.log('e', e)
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            this.paginationInfo.currentPage = 1
            this.formData.keyword = searchKey
            this.getTableData()
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        goList () {
            this.viewList = true
        },
        handleCurrentChange (val) {
            console.log('handleCurrentChange: ', val)
            this.currentRow = val
        },
        onCancel () {
            this.viewList = true
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
        goCategoryManage () {
            this.$router.push('/categoryManage')
        },
        onSave () {
            this.$refs.form.validate(valid=>{
                if(valid) {
                    this.formDataDetail.outerTypeKey = this.outsourcerType[this.formDataDetail.outerTypeValue]
                    if(this.viewList === 'add') {
                        addEvaluationPeriod(this.formDataDetail).then(()=>{
                            this.clientPop('suc', '保存成功', ()=>{ this.viewList = true;this.paginationInfo.currentPage = 1;this.getTableData() })
                        })
                    }else if(this.viewList === 'edit') {
                        updatEevaluationPeriod(this.formDataDetail).then(()=>{
                            this.clientPop('suc', '保存成功', ()=>{ this.viewList = true;this.paginationInfo.currentPage = 1;this.getTableData() })
                        })
                    }
                }
            })

        },
        changeEquip (val) {
            console.log(val)
            const that = this
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/facilityplan/list/account/equipment', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [val], // 已选中id
                Title: '选择自有与租赁台账' // 标题
            }).then(val => {
                that.formDataDetail.equipmentNo = val[0].equipmentNo
                that.formDataDetail.accountId = val[0].accountId
            }).catch(err=>{
                alert(err)
            })
        },
        tableDbDelete (row) {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作', ()=>{
                deleteEvaluationPeriod({ id: row.id }).then(()=>{
                    this.clientPop('suc', '删除成功', ()=>{
                        this.getTableData()
                    })
                })
            })
        },
    }
}
</script>

<style lang="scss" scoped>
::v-deep.el-checkbox-group{
    display: flex;
}
::v-deep.el-checkbox{
    display: flex; align-items: center;
}
</style>
